package StudyCode.summary.mydatetime;

import java.time.*;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;

import static java.time.DayOfWeek.*;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CustomDateAdjuster {

	static TemporalAdjuster WEEKDAYS_WITH_NO_FRIDAY_13 = TemporalAdjusters
			.ofDateAdjuster(CustomDateAdjuster::getWeekDayNoFriday13);

	private static LocalDate getWeekDayNoFriday13(LocalDate date) {
		LocalDate newDate = date;

		DayOfWeek day = date.getDayOfWeek();
		if (day == SATURDAY || day == SUNDAY || (day == FRIDAY && date.getDayOfMonth() == 13)) {
			// 返回下周一
			newDate = date.with(TemporalAdjusters.next(MONDAY));
		}
		return newDate;
	}

	public static void main(String[] args) {
		LocalDate ld1 = LocalDate.of(2013, Month.DECEMBER, 12); // 星期四
		LocalDate ld2 = LocalDate.of(2013, Month.DECEMBER, 13); // 星期五
		LocalDate ld3 = LocalDate.of(2013, Month.DECEMBER, 14); // 星期六

		LocalDate ld1Adjusted = ld1.with(WEEKDAYS_WITH_NO_FRIDAY_13);
		System.out.println(ld1 + " 调整到 " + ld1Adjusted);

		LocalDate ld2Adjusted = ld2.with(WEEKDAYS_WITH_NO_FRIDAY_13);
		System.out.println(ld2 + " 调整到 " + ld2Adjusted);

		LocalDate ld3Adjusted = ld3.with(WEEKDAYS_WITH_NO_FRIDAY_13);
		System.out.println(ld3 + " 调整到 " + ld3Adjusted);

		// 调整 ZonedDateTime
		ZonedDateTime zdt = ZonedDateTime.of(ld2, LocalTime.of(8, 45), ZoneId.of("America/Chicago"));
		ZonedDateTime zdtAdjusted = zdt.with(WEEKDAYS_WITH_NO_FRIDAY_13);
		System.out.println(zdt + " 调整到 " + zdtAdjusted);
	}
}
